package xworker.swt.dataObject.bind.values;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
import xworker.swt.dataObject.bind.Value;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormater  implements Value {
    Thing thing;
    SimpleDateFormat sf;

    public DateFormater(Thing thing, String pattern){
        this.thing = thing;
        sf = new SimpleDateFormat(pattern);
    }

    @Override
    public Object getValue(Object value, DataObject dataObject, ActionContext actionContext) {
        String attributeName = thing.doAction("getAttributeName", actionContext);
        if(attributeName != null && !attributeName.isEmpty()){
            return sf.format(dataObject.getDate(attributeName));
        }else {
            if(value instanceof Date){
                return sf.format((Date) value);
            }else{
                return value;
            }
        }
    }

    public static DateFormater create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        String pattern = self.doAction("getPattern", actionContext);
        return new DateFormater(self, pattern);
    }
}
